#!/usr/bin/env ruby
require 'erb'

require_relative 'run.rb'

REMOTE_REGEX = %r{gitlab.com.gitlab-org/gitaly.git}

# Sanity check
%w[
  git@gitlab.com:gitlab-org/gitaly.git
  https://gitlab.com/gitlab-org/gitaly.git
  https://janedoe@gitlab.com/gitlab-org/gitaly.git
].each do |remote|
  abort "regex check failed failed for #{remote.inspect}" unless REMOTE_REGEX.match(remote)
end

def main(version)
  remote = capture!(%w[git remote get-url --push origin])
  unless REMOTE_REGEX.match(remote)
    abort "Git remote 'origin' must match #{REMOTE_REGEX}, got #{remote.inspect}"
  end

  run!(%w[make verify])
  run!(%w[make test])

  puts 'Testing for changed files'
  run!(%w[git diff --quiet --exit-code])

  puts 'Testing for staged changes'
  run!(%w[git diff --quiet --cached --exit-code])

  tag_name = "v#{version}"
  write_version_file(version)
  update_changelog(tag_name)
  version_msg = "Version #{version}"
  run!(%W[git commit -m #{version_msg}])
  run!(%W[git tag -a -m #{version_msg} #{tag_name}])

  # We use 'capture!' to prevent 'git show' from invoking 'less'.
  show_output = capture!(%W[git show --pretty #{tag_name}])
  puts show_output

  puts "Proceed to publish version #{version}? Enter 'Yes' to continue; Ctrl-C to abort"
  $stdout.flush
  abort unless $stdin.gets.chomp == 'Yes'

  run!(%W[echo git push origin HEAD #{tag_name}])
end

def write_version_file(version)
  version_file = 'VERSION'
  open(version_file, 'w') { |f| f.puts version }
  run!(%W[git add #{version_file}])
end

def update_changelog(version_string)
  changelog = 'CHANGELOG.md'
  content = IO.read(changelog).lines
  unreleased_line = "UNRELEASED\n"
  version_index = content.find_index { |l| l == unreleased_line }
  if version_index.nil?
    abort "no #{unreleased_line.inspect} line found in #{changelog}"
  end
  content[version_index] = version_string + "\n"
  IO.write(changelog, content.join)
  run!(%W[git add #{changelog}])
end

def error(msg)
  warn "#{$0}: #{msg}"
end

unless ARGV.count == 1
  warn "Usage: #{$0} VERSION"
  warn "Specify version as x.y.z"
  abort
end

directory_current_file = File.expand_path('..', __FILE__)
git_root_current_file = capture!(%w[git rev-parse --show-toplevel], directory_current_file).chomp
unless git_root_current_file == Dir.pwd
  error "#{$0}: this script must be run from the root of the Gitaly repository"
  abort
end

main(ARGV.first)
